#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2025 粤港澳大湾区（广东）国创中心

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.

File: PythonRightDlg.py
Desc: Right-side panel dialog for this application, including properties tree.
Author: xumanjia
Date: 2025-08-01
"""

from PyQt5.QtWidgets import QFrame, QWidget, QTreeWidget, QHBoxLayout, QVBoxLayout, QPushButton, QTreeWidgetItem
from PyQt5.QtGui import QIcon, QMouseEvent, QColor, QPainterPath, QKeyEvent
from PyQt5.QtCore import Qt, pyqtSignal
import functools
from enum import Enum
from Dialog.PythonObjectTree import *

class PropertyTree(QTreeWidget):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.setHeaderLabels(["属性", "值"])
        self.setColumnCount(2) # 设置为两列
        self.setAlternatingRowColors(True) # 设置交替行颜色
        self.setIndentation(15) # 设置缩进
 
        # 存储属性数据（用于后续处理）
        self.property_data = {}
      
    def clear_properties(self):
        """清空所有属性和数据"""
        self.clear()
        self.property_data = {}

    def set_property_data(self,
        display_name: str = "",
        obj_name: str = "",
        type_name: str = "",
        ObjXDir: float = 0.0,
        ObjYDir: float = 0.0,
        ObjZDir: float = 0.0,
    ):
        """
        设置属性数据（直接传入各个属性的值）
        :param display_name: 显示名称
        :param obj_name: 对象名称
        :param type_name: 类型名称
        :param obj_long: 长度
        :param obj_wide: 宽度
        :param obj_tall: 高度
        """
        data = {
            "Object": {
                "DisplayName": display_name,
                "ObjName": obj_name,
                "TypeName": type_name,
                "ObjXDir": ObjXDir,
                "ObjYDir": ObjYDir,
                "ObjZDir": ObjZDir
            }
        }
        self.update_properties(data)
 
    def update_properties(self, data):
        """
        根据传入的 data 更新属性框显示
        :param data: 字典，格式如:
            {
                "Object": {
                    "DisplayName": "零件",
                    "ObjName": "DOC PART1",
                    "TypeName": "doc_part",
                    "ObjLong": 100,
                    "ObjWide": 50,
                    "ObjTall": 20
                }
            }
        """
        self.clear_properties()  # 先清空
 
        if not data:  # 如果没有数据，直接返回
            return
 
        # 遍历数据，创建分组和属性
        for group_name, properties in data.items():
            group_item = QTreeWidgetItem([group_name, ""])
            group_item.setFirstColumnSpanned(True)
            self.addTopLevelItem(group_item)
 
            # 存储分组数据
            self.property_data[group_name] = {}
 
            # 添加属性
            for prop_name, prop_value in properties.items():
                item = QTreeWidgetItem([prop_name, str(prop_value)])
                group_item.addChild(item)
 
                # 存储属性数据
                self.property_data[group_name][prop_name] = prop_value
 
        # 展开所有节点
        self.expandAll()

class ObjectProperty(QFrame):
    def __init__(self, parent = None):
        super().__init__(parent)
        self.propertyTree = PropertyTree(self)
        self.setupUI()

    def setupUI(self):
        mainLayout = QVBoxLayout(self)
        mainLayout.addWidget(self.propertyTree)

class PythonRightView(QFrame):
    class RightView(Enum):
        ViewEditor = 0
        ViewProperty = 1

    sigRightSidePannelVisible = pyqtSignal(int, bool)

    def __init__(self, parent = None):
        super().__init__(parent)
        self.editor_script_widget = QWidget(self)
        self.objectProperty = ObjectProperty()
        self.sideBar = PythonTreeSideBar()
        self.sidePannel = PythonTreeSidePannel()
        self.updateUI()

    def updateUI(self):
        mainLayout = QHBoxLayout(self)
        mainLayout.setContentsMargins(0,0,0,0)
        mainLayout.setSpacing(2)
        mainLayout.addWidget(self.sidePannel)
        mainLayout.addWidget(self.sideBar)
        self.sideBar.setSidePannel(pannel=self.sidePannel)
        self.sideBar.buttonClicked.connect(lambda clickedButton: self.onSideButtonClicked(clickedButton))

    def onSideButtonClicked(self, clickedButton:QPushButton):
        if not clickedButton:
            return
        checked = clickedButton.isChecked()
        index = self.sideBar.getButtonIndex(clickedButton)
        otherButtonChecked = self.sideBar.uncheckOtherButtons(clickedButton)
        if checked:
            if self.sidePannel:
                self.sidePannel.setVisible(True)
                self.sigRightSidePannelVisible.emit(index, True)
                if index != self.sidePannel.currentIndex():
                    self.sidePannel.setCurrentIndex(index)

        else:
            if not otherButtonChecked and self.sidePannel:
                self.sidePannel.setVisible(False)
                self.sigRightSidePannelVisible.emit(index, False)


